export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader(callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/**
 * 获取url参数
 * @param {*} url 请求的URL
 * @param {*} name 参数名
 */
export function getUrlParameter(url, name) {
  const reg = RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let params = url.split('?')[1]
  let param = params.match(reg)
  if (param !== null) {
    return unescape(param[2])
  }
  return null
}

/*
 * 获取url域名地址（适用于http或https协议）
 */
export function getRoot(url) {
  let schema = url.split(":")[0];
  let domain = url.split('/'); //以"/"进行分割
  if (domain[2]) {
    domain = domain[2];
    return schema + "://" + domain;
  }
  return null;
}

/**
 * @description 格式化金额
 * @param number：要格式化的数字
 * @param decimals：保留几位小数 默认0位
 * @param decPoint：小数点符号 默认.
 * @param thousandsSep：千分位符号 默认为,
 */
export const formatMoney = (number, decimals = 0, decPoint = '.', thousandsSep = ',') => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  let n = !isFinite(+number) ? 0 : +number
  let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  let sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  let dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  let s = ''
  let toFixedFix = function (n, prec) {
    let k = Math.pow(10, prec)
    return '' + Math.ceil(n * k) / k
  }
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  let re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
/**
 * @description 为为date原型挂在format方法,传入需要装换的格式
 * @param {yyyy-MM-dd} fmt 
 */
Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份 
    "d+": this.getDate(), //日 
    "h+": this.getHours(), //小时 
    "m+": this.getMinutes(), //分 
    "s+": this.getSeconds(), //秒 
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
    "S": this.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

/**
 * 格式化秒 返回小时、分钟
 * @param {} second 
 */
export function formatSecond(second) {
  if (second < 60) {
    return second + '秒'
  } else if (second < 3600) {
    return Math.floor(second / 60) + '分钟'
  } else {
    let hour = Math.floor(second / 3600);
    let minute = Math.floor((second - (hour * 3600)) / 60);
    if (minute == 0) {
      return hour + '小时'
    } else {
      return hour + '小时' + minute + '分钟'
    }
  }
}

/**
 * 获取cookie值
 * @param {*} name 
 */
export const getCookie = (name) => {
  var strcookie = document.cookie; //获取cookie字符串
  var arrcookie = strcookie.split("; "); //分割
  //遍历匹配
  for (var i = 0; i < arrcookie.length; i++) {
    var arr = arrcookie[i].split("=");
    if (arr[0] == name) {
      return arr[1];
    }
  }
  return "";
}

/**
 * 图片转base64
 * @param {*} img image对象
 */
export const imageToBase64 = (img) => {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
  var dataURL = canvas.toDataURL("image/jpeg" + ext);
  return dataURL;
}

/**
 * base64格式转为File文件类型
 * @param {*} urlData base64格式
 * @param {*} fileName  文件名称
 */
export const base64ToFile = (urlData, fileName) => {
  let arr = urlData.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bytes = atob(arr[1]); // 解码base64
  let n = bytes.length
  let ia = new Uint8Array(n);
  while (n--) {
    ia[n] = bytes.charCodeAt(n);
  }
  return new File([ia], fileName, {
    type: mime
  });
}

/**
 * 生成随机字符串
 * @param {*} length 字符长度 
 */
export function randomStr(length) {
  let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  ];
  let str = ''; // 最终字符
  for (let i = 0; i < length; i++) {
    let m = Math.floor(Math.random() * (arr.length)); //生成随机数
    str += arr[m];
  }
  return str;
}

/**
 * 下载文件
 * @param {*} response 
 * @param {*} fileName 文件名称
 */
export function downloadFile(response, fileName) {
  let blob = new Blob([response])
  let downloadElement = document.createElement('a');
  let href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  downloadElement.download = fileName; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放掉blob对象 
}

/**
 * 获取文件base64
 * @param {*} file 
 * @returns 
 */
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

import { KKFILE_URL } from '@/store/mutation-types.js'
import { Base64 } from 'js-base64'
/**
 * kkfile文件预览
 * @param {*} url 
 * @returns 
 */
export function kkfilePreview(url) {
  const fileType = url.substring(url.lastIndexOf('.') + 1)
  if (fileType && fileType.toLowerCase() !== 'jpg' && fileType.toLowerCase() !== 'jpeg' && fileType.toLowerCase() !== 'png') {
    url = url.replace('10.19.196.63', '172.21.61.230:6098')
  }
  // 修改kkfile文件预览，需要进行base64编码
  return KKFILE_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
}

import { VUE_APP_WEBOFFICE_URL } from '@/store/mutation-types.js'

// 在线文件编辑地址
export function webofficeEdit(url) {
  url = url.replace('10.19.196.63', '172.21.61.230:6098')
  // 修改kkfile文件预览，需要进行base64编码
  return  `${VUE_APP_WEBOFFICE_URL}?action=view&filepath=${url}`
}


/**
 * 文件预览
 * @param {*} url 文件地址
 * @returns
 */
 export function filePreview(url) {
  let suffix = url.substring(url.length - 4, url.length)
  if (suffix.toLowerCase() == '.pdf') {
    return process.env.VUE_APP_PDFJS + '?file=' + url
  } else {
    return url
  }
}

/**
 * docx文件在线编辑
 * @param {*} filePath 网络docx文件地址
 * @returns
 */
 export function docxEditOnile(filePath) {
  return process.env.VUE_APP_DOCXEDIT + '?action=view&filepath=' +  filePath
}

/**
 * 文件大小, 多少兆
 * @param size
 * @returns {string|*}
 */
 export function getFileSize(size) {
  if (!size) return ''
  if (size < pow1024(3)) return (size / pow1024(2)).toFixed(2)
}

// 求次幂
function pow1024(num) {
  return Math.pow(1024, num)
}

/**
 * 深度clone方法 利用json序列化无法实现对对象里的function进行克隆
 */
export function deepClone (obj) {
  var deepCopy = function (obj) {
    // 判断是否是对象
    if (typeof obj !== 'object') return;
    // 判断obj类型，根据类型新建一个对象或者数组
    var newObj = obj instanceof Array ? [] : {}
    // 遍历对象，进行赋值
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) {
        let val = obj[key];
        // 判断属性值的类型，如果是对象，递归调用deepCopy
        newObj[key] = typeof val === 'object' ? deepCopy(val) : val
      }
    }
    return newObj
  }
  return deepCopy(obj)
}


/**
 * 下载文件
 * @param {*} response 
 * @param {*} fileName 文件名称
 */
export function downloadFileWithUrl (fileUrl, fileName) {
  let x = new XMLHttpRequest()
  x.open('GET', fileUrl, true)
  x.responseType = 'blob'
  x.onload = function (e) {
    let url = window.URL.createObjectURL(x.response)
    let a = document.createElement('a')
    a.href = url
    a.download = fileName
    a.click()
  }
  x.send()
}